package com.rongzhe.house.easypoi.handler;

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.WordImageEntity;
import com.rongzhe.house.common.resp.ApiResult;
import com.rongzhe.house.common.utils.DateUtil;
import com.rongzhe.house.common.utils.QiniuFileUploadUtil;
import com.rongzhe.house.common.utils.math.NumberArithmeticUtils;
import com.rongzhe.house.easypoi.dto.ImagePath;
import com.rongzhe.house.easypoi.dto.RentInfoDTO;
import com.rongzhe.house.easypoi.util.ConvertUtil;
import com.rongzhe.house.easypoi.util.DownloadImage;
import com.rongzhe.house.easypoi.util.WordConvertPDF;
import com.rongzhe.house.house.dao.HouseBaseMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Description:   </p>
 * <p>Copyright: Copyright (c) 2018</p>
 *
 * @author admin
 * @version 1.0
 * @date 2018/8/1
 */
@Component
@Slf4j
public class HouseContractHandler {

    private final HouseBaseMapper houseBaseMapper;

    private final DeleteFileHandler deleteFileHandler;

    @Autowired
    public HouseContractHandler(HouseBaseMapper houseBaseMapper, DeleteFileHandler deleteFileHandler) {
        this.houseBaseMapper = houseBaseMapper;
        this.deleteFileHandler = deleteFileHandler;
    }

    /**
     * 生成合同
     *
     * @param map 合同数据
     * @return 输出的字节流
     */
    private ByteArrayOutputStream previewContract(Map<String, Object> map) {
        try {
            XWPFDocument doc = WordExportUtil.exportWord07("doc/contract.docx", map);
            ByteArrayOutputStream fos = new ByteArrayOutputStream();
            doc.write(fos);
            return fos;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("合同生成失败找不到合同",e);
        }
        return null;
    }

    /**
     * 预览合同
     *
     * @param rentInfoDTO
     * @return
     */
    public ApiResult previewContract(RentInfoDTO rentInfoDTO) {
        // 预览
        return handlerRentInfo(rentInfoDTO, "preview/");
    }

    /**
     * 持久合同
     *
     * @param rentInfoDTO
     * @return
     */
    public ApiResult longTermContract(RentInfoDTO rentInfoDTO) {
        return handlerRentInfo(rentInfoDTO, "forever/");
    }

    private ApiResult handlerRentInfo(RentInfoDTO rentInfoDTO, String imgPrefix) {
        ImagePath imagePath = null;
        StringBuffer buffer = new StringBuffer();
        buffer.append(imgPrefix);
        buffer.append(DateUtil.getFormatDateTime(new Date(), DateUtil.NO_SEPARATOR_SSS));
        buffer.append(".pdf");
        // 七牛云存储的文件名
        String pdfName = buffer.toString();
        // 上传文件后的七牛云文件
        String imgPath;

        ByteArrayOutputStream fileOutputStream = null;
        ByteArrayInputStream parse =null;
        ByteArrayOutputStream arrayOutputStream = null;
        try {


            // 2 处理图片信息
            imagePath = handlerImage(rentInfoDTO);
            // 3 处理后的map数据
            Map<String, Object> result = this.handlerMapData(rentInfoDTO, imagePath);
            // 4 获取处理后的文件流
            fileOutputStream=previewContract(result);
            // 5.将处理后的文件流转换为输出流 合同文件
            parse=ConvertUtil.parse(fileOutputStream);
            // 存放处理后的流 将要上传的流pdf
            arrayOutputStream = new ByteArrayOutputStream();
            // 4 将文件转换pdf
            WordConvertPDF.converFile(parse, arrayOutputStream);
            // 5 将pdf上传到七牛云
            // 6 返回图片路径
            imgPath = QiniuFileUploadUtil.uploadContract(arrayOutputStream.toByteArray(), pdfName);
        } catch (Exception e) {
            log.error("生成合同失败", e);
            // 7 删除所有临时信息
            deleteFileHandler.deleteFileInfo(imagePath);
            return ApiResult.buildFail("合同生成失败");
        } finally {

            try {
                if(arrayOutputStream !=null){
                    arrayOutputStream.close();
                }
                if(parse !=null){
                    parse.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        // 7 删除所有临时信息
        deleteFileHandler.deleteFileInfo(imagePath);
        return ApiResult.buildOk("操作成功", imgPath);
    }

    /**
     * 处理合同的map数据
     *
     * @param rentInfoDTO
     * @param imagePath
     * @return
     */
    private Map<String, Object> handlerMapData(RentInfoDTO rentInfoDTO, ImagePath imagePath) {
        Map<String, Object> map = new HashMap<>();
        map.put("currentDate", DateUtil.getFormatDateTime(new Date(), DateUtil.yyyyMMddChineseFormat));
        map.put("rentName", rentInfoDTO.getRentName());
        map.put("rentStart", format(rentInfoDTO.getRentStart()));
        map.put("rentEnd", format(rentInfoDTO.getRentEnd()));
        map.put("rentDate", map.get("rentStart") + "至" + map.get("rentEnd"));

        map.put("rentTerm", rentInfoDTO.getRentTerm());
        map.put("payMethod", rentInfoDTO.getPayMethod());

        map.put("payCount", rentInfoDTO.getPayCount());
        String deposit = rentInfoDTO.getDeposit().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
        map.put("deposit", deposit);
        map.put("depositChinese", NumberArithmeticUtils.numToChinese(deposit));

        String monthRent = rentInfoDTO.getMonthRent().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
        map.put("monthRent", monthRent);
        map.put("monthRentChinese", NumberArithmeticUtils.numToChinese(monthRent));

        String monthFee = rentInfoDTO.getMonthFee().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
        map.put("monthFee", monthFee);
        map.put("monthFeeChinese", NumberArithmeticUtils.numToChinese(monthFee));

        map.put("rentSex", rentInfoDTO.getRentSex());
        map.put("rentMobile", rentInfoDTO.getRentMobile());
        map.put("certificateType", "身份证");
        map.put("certificateNo", rentInfoDTO.getCertificateNo());
        // 处理图片
        handlerImage(imagePath, map);

        map.put("houseAddress", rentInfoDTO.getHouseAddress());
        map.put("houseArea", rentInfoDTO.getArea());

        map.put("rongZheAddress", rentInfoDTO.getRongzheAddress());

        String contractRemark = rentInfoDTO.getContractRemark();
        if (StringUtils.isNotBlank(contractRemark)) {
            map.put("contractRemark", contractRemark);
        } else {
            map.put("contractRemark", "无");
        }
        String publicList = rentInfoDTO.getPublicList();
        if (StringUtils.isNotBlank(publicList)) {
            map.put("publicList", publicList);
        } else {
            map.put("publicList", "无");
        }
        String privateList = rentInfoDTO.getPrivateList();
        if (StringUtils.isNotBlank(privateList)) {
            map.put("privateList", privateList);
        } else {
            map.put("privateList", "无");
        }
        String otherList = rentInfoDTO.getOtherList();
        if (StringUtils.isNotBlank(otherList)) {
            map.put("otherList", otherList);
        } else {
            map.put("otherList", "无");
        }
        return map;
    }

    /**
     * 处理图片数据
     *
     * @param imagePath
     * @param map
     */
    private void handlerImage(ImagePath imagePath, Map<String, Object> map) {
        if (imagePath != null) {
            String image1 = imagePath.getCertificateImage1();
            if (StringUtils.isNotBlank(image1)) {
                WordImageEntity image = new WordImageEntity();
                image.setHeight(80);
                image.setWidth(80);
                image.setUrl(image1);
                image.setType(WordImageEntity.URL);
                map.put("certificateImage1", image);
            } else {
                map.put("certificateImage1", "无");
            }
            String image2 = imagePath.getCertificateImage2();
            if (StringUtils.isNotBlank(image2)) {
                WordImageEntity image = new WordImageEntity();
                image.setHeight(80);
                image.setWidth(80);
                image.setUrl(image1);
                image.setType(WordImageEntity.URL);
                map.put("certificateImage2", image);
            } else {
                map.put("certificateImage2", "无");
            }
        } else {
            map.put("certificateImage1", "无");
            map.put("certificateImage2", "无");
        }
    }


    /**
     * 处理图片
     *
     * @param rentInfoDTO
     * @return
     */
    private ImagePath handlerImage(RentInfoDTO rentInfoDTO) {
        ImagePath imagePath = new ImagePath();
        boolean flag = false;
        if (StringUtils.isNotBlank(rentInfoDTO.getCertificateImage1())) {
            String download = DownloadImage.download(rentInfoDTO.getCertificateImage1());
            flag = true;
            imagePath.setCertificateImage1(download);
        }
        if (StringUtils.isNotBlank(rentInfoDTO.getCertificateImage2())) {
            String downlod = DownloadImage.download(rentInfoDTO.getCertificateImage2());
            flag = true;
            imagePath.setCertificateImage2(downlod);
        }
        if (flag) {
            return imagePath;
        } else {
            return null;
        }
    }

    /**
     * 格式化时间
     *
     * @param date
     * @return
     */
    private String format(Date date) {
        return DateUtil.getFormatDateTime(date, DateUtil.yyyyMMddFormat);
    }
}
